﻿using HandleSign.DataBase.SignTime;
using HandleSign.Models;
using ServerPA.CompletPort.Util;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;

namespace HandleSign.DataBase.AfterClass
{

    /// <summary>
    ///  下课
    /// </summary>
    public class AfterClassDAl
    {

        /// <summary>
        /// 下课：处理所有事件 
        /// author cidychou
        /// </summary>
        public void HandleAfterClass(TaskNumModel taskNum, SignTimeDAL stDAL, DateTime afterTime)
        {

            stDAL.removeManualSign(taskNum.taskNumId);

            /// 第一条数据时，1 .判断是否超过事件的Rctime，是 --> 结束事件 (待写)
            ///2 .遍历所有taskNum判断是否有下课的课程
            /// 下课  处理所有事件
            if (taskNum.seList.Count > 0) //稳定后合并
            {

                /// 1、将 taskNum——even——user 转成  uesr:evenList   1：N
                List<int> uidList = stDAL.getUserId(taskNum.classId);


                LogUtil.PrintlnLog("该班级人数" + taskNum.classId, uidList.Count() + "人", "Main");

                List<SignReSolvedModel> srsList = new List<SignReSolvedModel>();

                /// 遍历班里的学生
                foreach (int id in uidList)
                {
                    SignReSolvedModel srs = new SignReSolvedModel(id);

                    List<SignTimeModels> newStList = new List<SignTimeModels>();

                    foreach (SignEven seItem in taskNum.seList)
                    {
                        userEvenModel ueModel = new userEvenModel();
                        newStList = seItem.Stlist.Where(u => u.userid == id).ToList();
                        int userScanStatus = newStList.Count > 0 ? newStList[0].scanStatus : 4; // 4 失败，１　成功
                        int evenState = seItem.EvenStatus;
                        int evenId = taskNum.seList.IndexOf(seItem);

                        ueModel.evenId = evenId;
                        ueModel.evenState = evenState;  //1  成功， 0，不成功
                        ueModel.signState = userScanStatus;
                        srs.srsRcTime = seItem.Rctime;
                        srs.ueModelList.Add(ueModel);
                    }

                    srsList.Add(srs);
                }

                /// 2、分别处理user中的even
                foreach (SignReSolvedModel srsItem in srsList)
                {
                    LogUtil.PrintlnLog("UserEvenModelList", srsItem.tostring(), "Main");
                    int srs_SignResult = handleSignResult(srsItem.ueModelList); // 处理最终结果

                    ///入库
                    string sResult = @"SELECT [srs_TaskNum] FROM [PhoneSign].[dbo].[P_SignReSolved] where srs_TaskNum = '" + taskNum.taskNumId + "' and srs_StuId = '" + srsItem.userId + "' ";

                    string insertResult = "insert into [PhoneSign].[dbo].[P_SignReSolved] (srs_TaskNum, srs_StuId, srs_SignResult, srs_RoomId, srs_ClassId,srs_Uptime,[srs_ClassEndTime])values('" + taskNum.taskNumId + "'," + srsItem.userId + "," + srs_SignResult + ",(select top 1 e_RoomId  from  [PhoneSign].[dbo].P_Events where  E_TaskNum = '"+taskNum.taskNumId+"'  order by e_RcTime)," + taskNum.classId + ",GETDATE(), convert(datetime, '" + afterTime + "', 120))";
                   // string insertResult = "insert into [PhoneSign].[dbo].[P_SignReSolved] (srs_TaskNum, srs_StuId, srs_SignResult, srs_RoomId, srs_ClassId,srs_Uptime,[srs_ClassEndTime])values('" + taskNum.taskNumId + "'," + srsItem.userId + "," + srs_SignResult + "," + taskNum.seList[0].RoomID + "," + taskNum.classId + ",GETDATE(), (SELECT  distinct [classEndtime] FROM [AccessDB].[dbo].[TaskBindNum]  where Stb_ScanTaskNum = '" + taskNum.taskNumId + "'))";
                    stDAL.insert(sResult, insertResult, taskNum.taskNumId, taskNum.taskNumType);

                }
            }
        }
        /// <summary>
        /// author  cidychou
        /// action  分析签到状态
        /// </summary>
        /// <param name="srsDict"></param>
        /// <returns>签到结果（1：已签到；2：迟到；3：早退；4：旷课  6: 迟到&&早退）</returns>
        public  int handleSignResult(List<userEvenModel> uemList)
        {
            int hsr_SignResult = 4; // 默认
            List<userEvenModel> uemListOf1 = uemList.Where(u => u.evenState == 1).ToList();  // 事件为1 ： 正常情况，2: 不符合条件的事件， 0 正在等待的事件

            List<userEvenModel> uemListOf2 = null;
            if (uemListOf1.Count > 0)
            {
                uemListOf2 = uemList.Where(u => u.evenId > uemListOf1[0].evenId && u.evenState == 2).ToList();  // 事件为2的事件
                int success2Count = uemListOf2.Where(u => u.signState == 1).ToList().Count;

                ////   确定签到状态
                if (uemListOf1.Count == 1)
                {
                    //-------------------   even == 1 的情况   ----------------------------------
                    int signState = uemListOf1[0].signState;
                    if (signState == 1)
                    {
                        hsr_SignResult = signState;
                    }
                    else if (uemListOf2.Count > 0) //正常事件签到失败时，判断非正常事件是否签到成功
                    {
                        hsr_SignResult = success2Count > 0 ? 2 : 4;
                    }
                }

                else
                {

                    //-------------------  even == N(N>=2) 的情况   -----------------------------
                    int success1Count = uemListOf1.Where(u => u.evenId > uemListOf1[0].evenId && u.signState == 1).ToList().Count;  ////除了even1 其他事件签到成功的次数

                    if (uemListOf1[0].signState == 1)  // 第一个事件签到成功的情况
                    {
                        hsr_SignResult = success1Count == uemListOf1.Count - 1 ? 1 : 3; //有一个签到失败就当他早退 否则签到成功
                    }
                    else  // 第一个事件 没有 签到成功的情况
                    {
                        //1.最后一个事件签到成功时，当他是迟到
                        if (uemListOf1[uemListOf1.Count - 1].signState == 1)
                        {
                            hsr_SignResult = 2; //迟到
                        }

                        /// ------ 剩下的情况是 第一个事件和最后一次签到都没有签到成功，--------

                        //2.只有中间有一个事件签到成功时，既早退又迟到，否则旷课 

                        else if (success1Count > 0)
                        {
                            hsr_SignResult = 6; //既早退又迟到
                        }
                        //3. 没有一个正常事件签到成功时
                        else if (uemListOf2.Count > 0)
                        {
                            hsr_SignResult = success2Count == 0 ? 4 : 6;  // 当未成立事件  有一个以上就当 既早退又迟到



                            //int uemListOf3Middle = uemListOf2.Where(u => u.evenId > uemListOf2[0].evenId && u.evenId < uemListOf2[uemListOf2.Count - 1].evenId && u.evenState == 1).ToList().Count;
                            //int uemListOf3Late = uemListOf2.Where(u => u.evenId > uemListOf2[uemListOf2.Count - 1].evenId && u.evenState == 1).ToList().Count;

                            // if (uemListOf3Middle > 0 && uemListOf3Late > 0)

                            //if (uemListOf3Middle == 0 && uemListOf3Late == 0)
                            //{
                            //    hsr_SignResult = 4; //旷课
                            //}
                            //else if (uemListOf3Middle + uemListOf3Late == uemListOf2.Count)
                            //{
                            //    hsr_SignResult = 3; //早退？迟到
                            //                         hsr_SignResult = 2; //迟到
                            //}
                            //else
                            //{
                            //    hsr_SignResult = 3; //早退？迟到
                            //}
                        }

                    }
                }
            }
            return hsr_SignResult;
        }
       
    }
}